package com.bulls.dsp.service.impl;

import com.bulls.dsp.bean.enums.AidType;
import com.bulls.dsp.bean.mybatis.Aid;
import com.bulls.dsp.common.Constant;
import com.bulls.dsp.common.PageInfo;
import com.bulls.dsp.exception.UnknownTypeException;
import com.bulls.dsp.mapper.AidMapper;
import com.bulls.dsp.service.IAidService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class AidServiceImpl implements IAidService {

    @Resource
    private AidMapper aidMapper;

    @Override
    public void insert(Aid aid) {
        this.convertEnumsValue2Code(aid);
        if (aid.getId() == null) {
            aidMapper.insert(aid);
        } else {
            aidMapper.update(aid);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<?> findAllByIfNotNull(String name, int currentPage, int pageSize) {

        name = StringUtils.isEmpty(name) ? name : "%" + name.trim() + "%";
        List<Aid> aids = aidMapper.getAids(name, currentPage, pageSize);
        this.convertEnumsCode2Value(aids);

        return PageInfo.builder()
                .totalElements(aidMapper.getAidCount(name))
                .number(currentPage)
                .size(pageSize)
                .content(aids)
                .build();
    }

    private void convertEnumsCode2Value(List<Aid> aids) {
        aids.forEach(aid -> aid.setAidType(
                Optional.ofNullable(aid.getAidType())
                        .map(AidType::getByStringCode)
                        .map(AidType::getType)
                        .orElse(Constant.UNKNOWN)
        ));
    }

    private void convertEnumsValue2Code(Aid aid) {
        aid.setAidType(
                Optional.ofNullable(aid.getAidType())
                        .map(AidType::getByStringValue)
                        .map(AidType::getValue)
                        .map(String::valueOf)
                        .orElseThrow(UnknownTypeException::new)
        );
    }

    @Override
    public Map<String, List<List<String>>> getEnumsList() {

        Map<String, List<List<String>>> result = new HashMap<>();
        result.put("aidType", AidType.getCodeValueList());

        return result;
    }
}
